﻿using System;

namespace SampleCode.VirtualFS
{
    [Serializable]
    internal class FsInternalFileInfo
    {
        // Fields

        [NonSerialized]
        private bool _isOpenForReading;
        [NonSerialized]
        private bool _isOpenForWriting;

        public DateTime TimeCreated = DateTime.Now;
        public DateTime TimeModified = DateTime.Now;

        public int Start;
        public int Length;

        // a helper property
        public int End { get { return Start + Length; } }

        public bool IsOpenForReading    { get { return _isOpenForReading; } }
        public bool IsOpenForWriting    { get { return _isOpenForWriting; } }
        public bool IsOpen              { get { return _isOpenForReading || _isOpenForWriting; } }

        //TODO: a drawback with blocking here is that when first one stream is opened for reading, then yet another one is opened for reading and then the first is closed, the second one becomes unreadable.
        public bool Block(bool forWriting)
        {
            // if trying to open for writing
            if (forWriting)
            {
                if(_isOpenForReading || _isOpenForReading)
                    return false;
            }
            else // if (forReading)
            {
                if (IsOpenForWriting)
                    return false;
            }

            _isOpenForReading = !forWriting;
            _isOpenForWriting = forWriting;
            return true;
        }

        public void Unblock()
        {
            _isOpenForReading = _isOpenForWriting = false;
        }

        public override string ToString()
        {
            return string.Format
            (
                "Start: {0}, Length: {1}, Created: {2}, Modified: {3}, Block: {4}",
                Start,
                Length,
                TimeCreated,
                TimeModified,
                (IsOpenForReading ? "r" : "") + (IsOpenForWriting ? "w" : "")
            );
        }
    }
}
